#!/bin/sh
if [ -z "$2" ]; then
    echo "Usage: $0 {start|stop|restart|status} {cluster}"
    exit
fi

BASE_DIR=/home/statsd
BASE_NAME=$2
CONFIG=$BASE_DIR/config-$BASE_NAME
LOG_FILE=$BASE_DIR/logs/$BASE_NAME.log
LOG_PROXY_FILE=$BASE_DIR/logs/$BASE_NAME-proxy.log
FILES=`ls $CONFIG | grep $BASE_NAME-config`
PROXY_FILE=`ls $CONFIG | grep $BASE_NAME-proxyConfig | head -n1`


start_statsd_proxy() {
    cd $BASE_DIR
    if [ -z "$(ps -u statsd -f | grep $PROXY_FILE)" ]; then
        su statsd -c "nohup node statsd/proxy.js $CONFIG/$PROXY_FILE >> $LOG_PROXY_FILE 2>&1 &"
        echo "Start proxy succ, config=$PROXY_FILE."
    else
        echo "proxy had run, config=$PROXY_FILE."
    fi
}
start_statsd() {
    pushd $BASE_DIR
    for file in $FILES; do
        if [ -z "$(ps -u statsd -f | grep $file)" ]; then
            su statsd -c "nohup node statsd/stats.js $CONFIG/$file >> $LOG_FILE 2>&1 &"
            echo "Start statsd succ, config=$file."
        else
            echo "stasd had run, config=$file."
        fi
    done
    popd
}

stop_statsd_proxy() {
    pkill -ef -u statsd $BASE_NAME-proxyConfig
}

stop_statsd() {
    pkill -ef -u statsd $BASE_NAME-config
}

do_start() {
    start_statsd
    sleep 1
    start_statsd_proxy
}

do_stop() {
    stop_statsd_proxy
    stop_statsd
}

if [ "$1" = "start" ]; then
    read -p "Enter 'yes' to confirm start with config.d=$CONFIG: " answer
    if [ "$answer" != "yes" ]; then
        exit
    fi
    do_start
elif [ "$1" = "stop" ]; then
    read -p "Enter 'yes' to confirm stop with config.d=$CONFIG: " answer
    if [ "$answer" != "yes" ]; then
        exit
    fi
    do_stop
elif [ "$1" = "restart" ]; then
    read -p "Enter 'yes' to confirm restart with config.d=$CONFIG: " answer
    if [ "$answer" != "yes" ]; then
        exit
    fi
    do_stop
    sleep 1
    do_start
elif [ "$1" = "status" ]; then
    pid=$(pgrep -f -u statsd $BASE_NAME)
    if [ -z "$pid" ]; then
        echo "statsd-$BASE_NAME not running"
    else
        echo "statsd-$BASE_NAME is running $pid"
    fi
else
    echo "Usage: $0 {start|stop|restart|status} {cluster}"
fi
